package mark.tom.friend.roll.test

import android.content.DialogInterface
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
import mark.tom.friend.FRoll
import mark.tom.friend.roll.test.koltin.R

class MainActivity : AppCompatActivity() {

    private var mDialog: AlertDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // 设置当前的应用包名
        appPackageNameTextView.text = packageName
        // 设置文字的上下滚动
        appServerConfigTextView.movementMethod = ScrollingMovementMethod.getInstance()
        appExtraConfigTextView.movementMethod = ScrollingMovementMethod.getInstance()
        // 设置刷新按钮点击事件
        contentRefreshBtn.setOnClickListener {
            // 刷新内容
            refreshContent()
        }
        // 设置切换包名按钮点击事件
        packageNameChangeBtn.setOnClickListener {
            if (null == mDialog) {
                mDialog = createDialog()
            }
            if (!mDialog!!.isShowing) {
                mDialog!!.show()
            }
        }
        // 刷新数据并呈现在界面上
        refreshContent()
    }

    private fun createDialog(): AlertDialog {
        return AlertDialog.Builder(this, R.style.Theme_AppCompat_Light_Dialog_Alert)
                .setTitle(R.string.dialog_title)
                .setView(R.layout.dialog_package_switch)
                .setPositiveButton(android.R.string.ok, DialogInterface.OnClickListener { dialog, which ->
                    val packageNameEditText = mDialog!!.findViewById(R.id.packageNameEditText) as TextView? ?: return@OnClickListener
                    var packageName = packageNameEditText.text.toString()
                    if (TextUtils.isEmpty(packageName)) {
                        packageName = getPackageName()
                    }
                    appPackageNameTextView.text = packageName
                    // 刷新内容
                    refreshContent()
                })
                .setNegativeButton(android.R.string.no, null)
                .create()
    }

    private fun refreshContent() {
        val appSettingBean = FRoll.get(appPackageNameTextView.text.toString())
        appDebugAbleTextView.text = appSettingBean.isDebugAble.toString()
        appServerConfigTextView.text = appSettingBean.serverConfig
        appExtraConfigTextView.text = appSettingBean.extraConfig
    }
}